package cn.mrlong.base.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.provider.Settings;

import java.lang.reflect.Method;

/**
 * 设置飞行模式
 */
public class FlightModeUtil {
    public static void setMode(Context context) {
        ContentResolver cr = context.getContentResolver();
        if (Settings.System.getString(cr, Settings.System.AIRPLANE_MODE_ON).equals("0")) {
            //获取当前飞行模式状态,返回的是String值0,或1.0为关闭飞行,1为开启飞行
            //如果关闭飞行,则打开飞行
            Settings.System.putString(cr, Settings.System.AIRPLANE_MODE_ON, "1");
            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            context.sendBroadcast(intent);
            //ToastUtil.showMsg("开启飞行");
        } else {
            Settings.System.putString(cr, Settings.System.AIRPLANE_MODE_ON, "0");
            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            context.sendBroadcast(intent);
            //oastUtil.showMsg("关闭飞行");
        }
    }

    /**
     * GPRS网络开关 反射ConnectivityManager中hide的方法setMobileDataEnabled 可以开启和关闭GPRS网络
     *
     * @param isEnable
     * @throws Exception
     */

    public static void toggleGprs(boolean isEnable, Context context) {
        try {
            ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            Class<?> cmClass = connManager.getClass();
            Class<?>[] argClasses = new Class[1];
            argClasses[0] = boolean.class;

            // 反射ConnectivityManager中hide的方法setMobileDataEnabled，可以开启和关闭GPRS网络
            Method method = cmClass.getMethod("setMobileDataEnabled", argClasses);
            method.invoke(connManager, isEnable);
            //ToastUtil.showMsg("==");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
